package com.esunny.springboot.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.esunny.springboot.constant.Constants;
import com.esunny.springboot.constant.UserConstants;
import com.esunny.springboot.exception.BaseException;
import com.esunny.springboot.mapper.UserAuthorityMapper;
import com.esunny.springboot.mapper.UserMapper;
import com.esunny.springboot.mapper.UserRoleMapper;
import com.esunny.springboot.pojo.dto.LoginUser;
import com.esunny.springboot.pojo.dto.Permissions;
import com.esunny.springboot.pojo.entity.User;
import com.esunny.springboot.pojo.entity.UserRole;
import com.esunny.springboot.service.LoginInfoService;
import com.esunny.springboot.service.UserService;
import com.esunny.springboot.utils.SecurityUtils;
import com.esunny.springboot.utils.StringUtils;
import com.esunny.springboot.utils.enums.UserStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * <p>
 * 表名全称:t_user  用户表。 服务实现类
 * </p>
 *
 * @author 罗滔
 * @since 2020-10-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAuthorityMapper userAuthorityMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private LoginInfoService loginInfoService;


    /**
     * 登录
     */
    @Override
    public LoginUser login(String username, String password) {

        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            loginInfoService.add(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new BaseException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            loginInfoService.add(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new BaseException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            loginInfoService.add(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new BaseException("用户名不在指定范围");
        }
        // 查询用户信息（user和权限和角色）
        LoginUser userResult = info(username);
        User userInfo = userResult.getUser();
        if (UserStatus.DELETED.getCode().equals(userInfo.getStatus())) {
            loginInfoService.add(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new BaseException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(userInfo.getStatus())) {
            loginInfoService.add(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        }
        if (!SecurityUtils.matchesPassword(password, userInfo.getPassword())) {
            loginInfoService.add(username, Constants.LOGIN_FAIL, "用户密码错误");
            throw new BaseException("用户不存在/密码错误");
        }
        loginInfoService.add(username, Constants.LOGIN_SUCCESS, "登录成功");
        userInfo.setPassword(null);
        return userResult;
    }


    @Override
    public void logout(String loginName) {
        loginInfoService.add(loginName, Constants.LOGOUT, "退出成功");
    }

    @Override
    public void addUser(String userName, String password, Permissions permissions, Long parentId, long role) throws Exception {
        if (StringUtils.isNotNull(userMapper.selectUserByUsername(userName))) {
            throw new Exception("用户名: " + userName + " 已存在!");
        }
        userMapper.insertUser(userName, SecurityUtils.encryptPassword(password), parentId);
        Long userId = userMapper.selectUserByUsername(userName).getUserId();
        userAuthorityMapper.insertUserAuthority(userId, permissions.getPermissions());
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(role);
        userRoleMapper.insert(userRole);
    }

    @Override
    public void deleteUser(String userName) {
        Long userId = userMapper.selectUserByUsername(userName).getUserId();
        userMapper.deleteByPrimaryKey(userId);
        userRoleMapper.deleteRole(userId);
        userAuthorityMapper.deleteByUserId(userId);
    }

    @Override
    public void updatePassword(String userName, String password, String newPassword) {
        User user = userMapper.selectUserByUsername(userName);
        if (!SecurityUtils.matchesPassword(password, user.getPassword())) {
            throw new BaseException("密码错误");
        }
        userMapper.updatePassword(userName, SecurityUtils.encryptPassword(newPassword));

    }

    @Override
    public void updateRole(String userName, String role) {
    }

    @Override
    public void updateChildPermissions(String userName, Permissions permissions) {
    }

    @Override
    public void getSuperAdminPermissions() {

    }

    @Override
    public Set<String> getUserPermissions(String userName) {
        User user = userMapper.selectUserByUsername(userName);
        Set<String> permissions = userAuthorityMapper.getUserAuthority(user.getUserId());
        return permissions;
    }


    /**
     * 获取当前用户信息(user、权限、角色)
     */
    public LoginUser info(String username) {
        //其实表里可以设置个登录状态，在登录时判断用户是否已经登录
        User user = userMapper.selectUserByUsername(username);
        if (StringUtils.isNull(user)) {
            throw new BaseException("登录用户：" + username + " 不存在");
        }

        // 用户是什么角色
        Long role = userRoleMapper.selectRoleByUserId(user.getUserId());
        // 用户具备的权限集合
        Set<String> permissions = userAuthorityMapper.getUserAuthority(user.getUserId());
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setUser(user);
        sysUserVo.setRole(role);
        sysUserVo.setPermissions(permissions);
        return sysUserVo;
    }
}
